//发送
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
struct msgbuf{
    long mtype;//消息类型
    char mtext[128];//内容
};
char time_str[20];
char* gettime(){//获取当前时间
    time_t now;
    struct tm *local_time;
    now = time(NULL);
    local_time = localtime(&now);
    strftime(time_str, sizeof(time_str),"%Y-%m-%d %H:%M:%S", local_time);
    return time_str;
}
int main(){
    printf("\t\t10180824--徐壮壮--Sender\n");
    //创建和获取消息队列
    int msgId = msgget(0x666, IPC_CREAT|0777);
    int rcvFlag,sndFlag;
    struct msgbuf sndMsg={666,"null"};//发送给接受者信息
    struct msgbuf rcvMsg={888,""};//接收接收者的信息
    
    while(strcmp(sndMsg.mtext,"end")){
        //发送内容
        printf("\t\t\t\t输入发送信息:\n\t\t\t\t");
        gets(sndMsg.mtext);
        sndFlag = msgsnd(msgId,&sndMsg,sizeof(sndMsg),0);
        if(sndFlag==0){
            printf("\t\t发送成功 %s\n",gettime());
        }else{
            printf("\t\t\t发送失败\n");    
        }
        //判断是否有未读消息
        if(rcvFlag = msgrcv(msgId,&rcvMsg,sizeof(sndMsg),888,0)){
            //如果消息队列有未读消息
            printf("收到消息 %s:\n%s\n",gettime(),rcvMsg.mtext);
        }
    }
    msgctl(msgId,IPC_RMID,NULL);   //将队列从系统内核中删除
    return 0;
}